<template>
  <div class="artList-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- form表单区域 -->
      <div>
        <el-form
          :inline="true"
          :model="formInline"
          class="demo-form-inline"
          :rules="queryFormRules"
          ref="queryForm"
        >
          <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="formInline.cate_id" placeholder="请选择分类">
              <el-option
                v-for="item in cateListObj"
                :label="item.cate_name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="筛选状态" prop="state">
            <el-select v-model="formInline.state" placeholder="请选择状态">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="initArtListFn">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="info" @click="resetListFn">重置</el-button>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button type="primary" @click="dialogVisible = true">发表文章</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- table表格显示数据 -->
      <div>
        <el-table :data="artList" border style="width: 100%">
          <el-table-column prop="title" label="文章标题">
            <template slot-scope="scope">
              <el-link type="primary">
                <span @click="showDetailFn(scope.row)"> {{ scope.row.title }}</span>
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="cate_name" label="分类"> </el-table-column>
          <el-table-column label="发表时间">
            <template slot-scope="scope">
              {{ scope.row.pub_date | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="danger" @click="delArt(scope.row, scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页标签 -->
        <el-pagination
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="1"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- dialog弹窗区域 -->
      <div>
        <el-dialog
          title="发表文章"
          :visible.sync="dialogVisible"
          :before-close="handleClose"
          fullscreen
        >
          <!-- 表单区域 -->
          <el-form
            :model="ruleForm"
            :rules="pubFormRules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <!-- 文章标题 -->
            <el-form-item label="文章标题" prop="title" class="title">
              <el-input v-model="ruleForm.title"></el-input>
            </el-form-item>
            <!-- 文章分类 -->
            <el-form-item label="文章分类" prop="cate_id">
              <el-select v-model="ruleForm.cate_id" placeholder="请选择文章分类">
                <el-option
                  v-for="item in cateListObj"
                  :label="item.cate_name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 文章内容 -->
            <el-form-item label="文章内容" prop="content">
              <!-- 使用 v-model 进行双向的数据绑定 -->
              <quill-editor v-model="ruleForm.content" @blur="onEditorChange"></quill-editor>
            </el-form-item>
            <!-- 文章封面 -->
            <el-form-item label="文章封面" prop="cover_img">
              <img ref="coverImg" src="" v-if="ruleForm.cover_img" />
              <img src="@/assets/images/cover.jpg" v-else />
              <input type="file" style="display: none" ref="coverFile" @change="changeCover" />
              <br />
              <i class="el-icon-plus" @click="chooseCover">&nbsp;选择封面</i>
            </el-form-item>
            <!-- 发布 -->
            <el-form-item prop="state">
              <el-button type="primary" @click="submit('已发布')">发布</el-button>
              <el-button type="info" @click="submit('草稿')">存为草稿</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <!-- 文章详情dialog -->
      <!-- 查看文章详情的对话框 -->
      <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
        <h1 class="title">{{ artDetail.title }}</h1>
        <div class="info">
          <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
          <span>发布时间：{{ artDetail.pub_date | formatDate }}</span>
          <span>所属分类：{{ artDetail.cate_name }}</span>
          <span>状态：{{ artDetail.state }}</span>
        </div>
        <!-- 分割线 -->
        <el-divider></el-divider>
        <!-- 文章的封面 -->
        <img v-if="artDetail.cover_img" :src="baseURL + artDetail.cover_img" />
        <!-- 文章的详情 -->
        <div v-html="artDetail.content" class="detail-box"></div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { getArtListAPI, addArticleAPI, getArticleAPI, getArtInfoAPI, delArtInfoAPI } from '@/api'
import dayjs from 'dayjs'
export default {
  data() {
    return {
      formInline: {
        state: '',
        cate_id: ''
      },
      ruleForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      // 表单规则
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: ['blur', 'change'] }
        ],
        cate_id: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
        content: [{ required: true, message: '请输入文章内容' }],
        cover_img: [{ required: true, message: '请选择文章封面' }]
      },
      queryFormRules: {
        cate_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
        state: [{ required: true, message: '请选择状态 ', trigger: 'change' }]
      },
      dialogVisible: false,
      // 分类数组对象
      cateListObj: [],
      // 文章列表
      artList: [],
      // 总页数
      total: null,
      // 每页条数
      pagesize: 5,
      // 当前页码
      pagenum: 1,
      detailVisible: false,
      artDetail: {},
      baseURL: 'http://big-event-vue-api-t.itheima.net'
    }
  },
  created() {
    this.getArtList()
    this.getArticle({ pagenum: 1, pagesize: 5 })
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    // 获取文章分类
    async getArtList() {
      const {
        data: { data }
      } = await getArtListAPI()
      console.log(data)
      this.cateListObj = data
    },
    // 点击选择封面
    chooseCover() {
      this.$refs.coverFile.click()
    },
    // 封面选择后处理函数
    changeCover(e) {
      const file = e.target.files[0]
      if (file) {
        this.ruleForm.cover_img = file
        const url = URL.createObjectURL(file)
        // 等待dom渲染完毕再执行代码，因为这个img使用了v-if，默认为假，所以一开始不显示，不存在这个标签
        this.$nextTick(() => {
          this.$refs.coverImg.setAttribute('src', url)
        })
      } else {
        this.ruleForm.cover_img = null
      }
      this.$refs.ruleForm.validateField('cover_img')
    },
    // 点击发布或则暂存按钮
    submit(status) {
      // eslint-disable-next-line
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.ruleForm.state = status
          // 1.创建FormData对象
          const fd = new FormData()
          // 2.往FormData对象追加数据
          for (const i in this.ruleForm) {
            fd.append(i, this.ruleForm[i])
          }
          // 3.发送请求
          const { data } = await addArticleAPI(fd)
          console.log(data)
          if (data.code === 0) {
            this.$message({
              message: '发布文章成功!',
              type: 'success'
            })
            this.dialogVisible = false
          } else {
            this.$message.error('发布文章失败!')
          }
          this.getArticle({ pagesize: this.pagesize, pagenum: this.pagenum })
        }
      })
    },
    // 富文本编辑器change事件
    onEditorChange() {
      this.$refs.ruleForm.validateField('content')
    },
    // 获取文章列表
    async getArticle(obj) {
      const { data } = await getArticleAPI(obj)
      console.log(data)
      this.artList = data.data
      this.total = data.total
    },
    // 当前页面改变
    handleCurrentChange(val) {
      this.pagenum = val
      this.getArticle({ pagenum: val, pagesize: this.pagesize })
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pagesize = val
      this.getArticle({ pagenum: this.pagenum, pagesize: val })
    },
    // 筛选重置按钮
    resetListFn() {
      this.getArticle({ pagenum: 1, pagesize: 5 })
    },
    // 筛选查询按钮
    initArtListFn() {
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          const obj = {
            pagenum: this.pagenum,
            pagesize: this.pagesize,
            cate_id: this.formInline.cate_id,
            state: this.formInline.state
          }
          this.getArticle(obj)
        }
      })
    },
    // 获取文章详情
    async getArtInfoAPI(obj) {
      const { data } = await getArtInfoAPI(obj)
      console.log(data)
      this.artDetail = data.data
    },
    // 点击显示文章详情
    showDetailFn(row) {
      console.log(row)
      this.getArtInfoAPI(row)
      this.detailVisible = true
    },
    // 删除文章
    async delArtInfo(delObj, i) {
      const { data } = await delArtInfoAPI(delObj)
      console.log(data)
      if (data.code === 0) {
        // this.artList.splice(i, 1)
        if (this.pagenum !== 1 && this.artList.length === 1) {
          this.pagenum--
          this.getArticle({ pagenum: this.pagenum, pagesize: this.pagesize })
        } else {
          this.getArticle({ pagenum: this.pagenum, pagesize: this.pagesize })
        }

        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      } else {
        this.$message.error('删除失败!')
      }
    },
    // 删除按钮
    delArt(obj, index) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delArtInfo(obj, index)
        })
        .catch(() => {
          this.$message({
            type: 'warning',
            message: '已取消删除!'
          })
        })
    }
  },
  watch: {
    dialogVisible(newVal) {
      if (newVal === false) {
        // 重置表单数据
        this.$refs.ruleForm.resetFields()
      }
    }
  },
  filters: {
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ql-editor {
  min-height: 300px;
}

img {
  width: 350px;
  height: 350px;
}
/deep/ .el-icon-plus {
  cursor: pointer;
  color: rgb(94, 174, 255);
}
.title {
  width: 320px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
::v-deep .detail-box {
  img {
    width: 500px;
  }
}
</style>
